package com.wjw.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * token工具类：
 * token由header.payload.signature组成
 */
public class JwtUtils {
    private static final String SECRET = "!@#asd123456";//秘钥
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 1.生成token:  header.payload.signature
     * @param map： 为payload中的参数
     * @return
     */
    public static String createToken(Map<String,String> map){
        Calendar canlendar = Calendar.getInstance();
        canlendar.add(Calendar.DATE,7);//7天token过期
        //创建JWT builder
        JWTCreator.Builder builder = JWT.create();
        //往payload中设置值
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        //指定token过期时间
        builder.withExpiresAt(canlendar.getTime());
        //生成token
        String token = builder.sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    /**
     * 2.验证token的合法性,不合法的token会抛出异常
     * @param token
     */
    public static void verifyToken(String token){
        JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }

    /**
     * 3.验证token的合法性,也能获取token中的信息
     * @param token
     * @return
     */
    public static DecodedJWT getTokenInfo(String token){
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }

    /**
     * 测试工具类
     * @param args
     */
    public static void main(String[] args) {
        Map<String,String> payloadMap = new HashMap<>();
        payloadMap.put("userId","11");
        payloadMap.put("userName","wjw123");
        //1.生成token
        String token = JwtUtils.createToken(payloadMap);
        System.out.println(token);
        //2.
        JwtUtils.verifyToken(token);
        //3.获取token中的信息
        DecodedJWT decodedJWT = JwtUtils.getTokenInfo(token);
        String header = decodedJWT.getHeader();//base64加密后的header
        String payload = decodedJWT.getPayload();//base64加密后的payload
        String signature = decodedJWT.getSignature();//signature
        //payloadMap中的具体值
        String userId = decodedJWT.getClaim("userId").asString();
        String userName = decodedJWT.getClaim("userName").asString();
        String expiresDate = dateFormat.format(decodedJWT.getExpiresAt());//过期时间
        System.out.println("header:"+header);
        System.out.println("payload:"+payload);
        System.out.println("signature:"+signature);
        System.out.println("userId:"+userId);
        System.out.println("userName:"+userName);
        System.out.println("expiresDate:"+expiresDate);
    }
}
